/*
 * User: ophir
 * Date: Sep 30, 2008
 * Time: 7:02:03 PM
 */
package org.conann.common;

import org.conann.exceptions.WebBeansSystemException;

import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentTasksExecutor {

    private final ExecutorService executorService = Executors.newCachedThreadPool();

    public void executeConcurrently(Collection<Runnable> tasks) {
        final CountDownLatch latch = new CountDownLatch(tasks.size());
        for (final Runnable task : tasks) {
            executorService.execute(new Runnable() {
                public void run() {
                    try {
                        task.run();
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new WebBeansSystemException("Counldn't coordinate tasks.", e);
        }
    }
}